package cn.stylefeng.guns.sys.modular.system.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import cn.stylefeng.guns.base.pojo.page.LayuiPageFactory;
import cn.stylefeng.guns.base.pojo.page.LayuiPageInfo;
import cn.stylefeng.guns.sys.modular.system.entity.DsstoreBill;
import cn.stylefeng.guns.sys.modular.system.mapper.DsstoreBillMapper;
import cn.stylefeng.guns.sys.modular.system.model.params.DsstoreBillParam;
import cn.stylefeng.guns.sys.modular.system.model.params.ItemBusUnitParam;
import cn.stylefeng.guns.sys.modular.system.model.result.DsstoreBillResult;
import cn.stylefeng.guns.sys.modular.system.service.DsstoreBillService;
import cn.stylefeng.guns.sys.modular.system.service.ItemInterfaceService;
import cn.stylefeng.roses.core.util.ToolUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.google.common.collect.Lists;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.Serializable;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author jiangge
 * @since 2020-09-15
 */
@Service
public class DsstoreBillServiceImpl extends ServiceImpl<DsstoreBillMapper, DsstoreBill> implements DsstoreBillService {
    private Logger logger = LoggerFactory.getLogger(DsstoreBillServiceImpl.class);
    private RestTemplate restTemplate = new RestTemplate();

    @Autowired
    private ItemInterfaceService itemInterfaceService;

    @Override
    public void add(DsstoreBillParam param) {
        DsstoreBill entity = getEntity(param);
        this.save(entity);
    }

    @Override
    public void delete(DsstoreBillParam param) {
        this.removeById(getKey(param));
    }

    @Override
    public void update(DsstoreBillParam param) {
        DsstoreBill oldEntity = getOldEntity(param);
        DsstoreBill newEntity = getEntity(param);
        ToolUtil.copyProperties(newEntity, oldEntity);
        this.updateById(newEntity);
    }

    @Override
    public DsstoreBillResult findBySpec(DsstoreBillParam param) {
        return null;
    }

    @Override
    public List<DsstoreBillResult> findListBySpec(DsstoreBillParam param) {
        return null;
    }

    @Override
    public LayuiPageInfo findPageBySpec(DsstoreBillParam param) {
        Page pageContext = getPageContext();
        IPage page = this.baseMapper.customPageList(pageContext, param);
        return LayuiPageFactory.createPageInfo(page);
    }

    @Override
    public Integer initDsstorebillData(String day) {
        String url = "http://btyjt.c3.fxscm.net/cldpoint/getDsstorebill.do?&ent=ENT7617&username=admin&password=admin123&busdate=" + day + "";
        String content = restTemplate.getForObject(url, String.class);
        JSONObject jsonObjectResult = JSON.parseObject(content);
        JSONArray jsonArray = jsonObjectResult.getJSONArray("data");

        /**
         * ShopCode    ShopName	ItemSmallClassName  ItemName
         * 没有店名查询的的是所有的店,把获取到的数据取出来便利 然后挨个插入到表中
         */
        JSONObject jsonObject;
        List<DsstoreBill> list = Lists.newLinkedList();
        for (int i = 0; i < jsonArray.size(); i++) {
            DsstoreBill dsstoreBill = new DsstoreBill();
            //把所有 ItemSmallClassName 为 酱料 的添加到list中
            jsonObject = jsonArray.getJSONObject(i);
            List<String> type = Lists.newLinkedList();
            type.add("门店统配入库");
            type.add("门店直配入库");
            type.add("门店自采入库");
            type.add("门店其他入库");
            type.add("门店期初单");
            type.add("店间调入");
            type.add("门店外销退货");
            type.add("门店冲减出库");
            type.add("门店报损出库");
            type.add("门店外销出库");
            type.add("门店统配退货单");
            type.add("门店部门领用");
            type.add("店内档口领用");
            type.add("店间调出");
            type.add("门店其他出库");
            type.add("门店自采退货");

            if ("酱料".equals(jsonObject.getOrDefault("ItemSmallClassName", "").toString())
                    && type.contains(jsonObject.getOrDefault("BillType", ""))
                    && !"山西配送中心".equals(jsonObject.getOrDefault("ShopName", "").toString())
                    && !"山东配送中心".equals(jsonObject.getOrDefault("ShopName", "").toString())) {
                dsstoreBill.setBillNo(jsonObject.getOrDefault("BillNO", "").toString());
                dsstoreBill.setOtherSideName(jsonObject.getOrDefault("OtherSideName", "").toString());
                dsstoreBill.setShopName(jsonObject.getOrDefault("ShopName", "").toString());
                dsstoreBill.setItemBigClassName(jsonObject.getOrDefault("ItemBigClassName", "").toString());
                dsstoreBill.setItemAssistNo(jsonObject.getOrDefault("ItemAssistNO", "").toString());
                dsstoreBill.setItemSpec(jsonObject.getOrDefault("ItemSpec", "").toString());
                dsstoreBill.setSellTaxes(convertToDecimal(jsonObject.getOrDefault("SellTaxes", "").toString()));
                dsstoreBill.setItemSmallClassCode(jsonObject.getOrDefault("ItemSmallClassCode", "").toString());
                dsstoreBill.setArriveMoney(convertToDecimal(jsonObject.getOrDefault("ArriveMoney", "").toString()));
                dsstoreBill.setStoreCode(jsonObject.getOrDefault("StoreCode", "").toString());
                dsstoreBill.setOutputRate(convertToDecimal(jsonObject.getOrDefault("outputRate", "").toString()));
                dsstoreBill.setStoreBillRemark(jsonObject.getOrDefault("StoreBillRemark", "").toString());
                dsstoreBill.setOutMainAmount(convertToDecimal(jsonObject.getOrDefault("OutMainAmount", "").toString()));
                dsstoreBill.setItemSign(jsonObject.getOrDefault("ItemSign", "").toString());
                dsstoreBill.setShopCode(jsonObject.getOrDefault("ShopCode", "").toString());
                dsstoreBill.setTaxMoney(convertToDecimal(jsonObject.getOrDefault("TaxMoney", "").toString()));
                dsstoreBill.setStoreBillDtid(jsonObject.getOrDefault("StoreBillDTID", "").toString());
                dsstoreBill.setModifyDate(convertToDate(jsonObject.getOrDefault("modifyDate", "").toString()));
                dsstoreBill.setStoreName(jsonObject.getOrDefault("StoreName", "").toString());
                dsstoreBill.setStoreBillidRemark(jsonObject.getOrDefault("StoreBillIDRemark", "").toString());
                dsstoreBill.setMainUnit(jsonObject.getOrDefault("MainUnit", "").toString());
                dsstoreBill.setGiftFlag(convertBooleanToInt(jsonObject.getOrDefault("GiftFlag", "").toString()));
                dsstoreBill.setOutStoreMoney(convertToDecimal(jsonObject.getOrDefault("OutStoreMoney", "").toString()));
                dsstoreBill.setItemId(jsonObject.getOrDefault("ItemID", "").toString());
                dsstoreBill.setItemSmallClassName(jsonObject.getOrDefault("ItemSmallClassName", "").toString());
                dsstoreBill.setStoreBillReState(convertBooleanToInt(jsonObject.getOrDefault("StoreBillReState", "").toString()));
                dsstoreBill.setBusUser(jsonObject.getOrDefault("BusUser", "").toString());
                dsstoreBill.setTaxes(convertToDecimal(jsonObject.getOrDefault("Taxes", "").toString()));
                dsstoreBill.setBatchCode(jsonObject.getOrDefault("BatchCode", "").toString());
                dsstoreBill.setInStoreMoney(convertToDecimal(jsonObject.getOrDefault("InStoreMoney", "").toString()));
                dsstoreBill.setIsOut(convertToInt(jsonObject.getOrDefault("isOut", "").toString()));
                dsstoreBill.setShopId(jsonObject.getOrDefault("ShopID", "").toString());
                dsstoreBill.setMakeTime(convertToDate(jsonObject.getOrDefault("MakeTime", "").toString()));
                dsstoreBill.setBillBusType(jsonObject.getOrDefault("BillBusType", "").toString());
                dsstoreBill.setProcessMoney(convertToDecimal(jsonObject.getOrDefault("processMoney", "").toString()));
                dsstoreBill.setItemCode(jsonObject.getOrDefault("ItemCode", "").toString());
                dsstoreBill.setPushOutStoreMoney(convertToDecimal(jsonObject.getOrDefault("PushOutStoreMoney", "").toString()));
                dsstoreBill.setInMainAmount(convertToDecimal(jsonObject.getOrDefault("InMainAmount", "").toString()));
                dsstoreBill.setPushOutStoreAmount(convertToDecimal(jsonObject.getOrDefault("PushOutStoreAmount", "").toString()));
                dsstoreBill.setStoreBillId(jsonObject.getOrDefault("StoreBillID", "").toString());
                dsstoreBill.setSellIncludeTaxMoney(convertToDecimal(jsonObject.getOrDefault("SellIncludeTaxMoney", "").toString()));
                dsstoreBill.setOutBusAmount(convertToDecimal(jsonObject.getOrDefault("OutBusAmount", "").toString()));
                dsstoreBill.setOtherSideType(jsonObject.getOrDefault("OtherSideType", "").toString());
                dsstoreBill.setPushInStoreMoney(convertToDecimal(jsonObject.getOrDefault("PushInStoreMoney", "").toString()));
                dsstoreBill.setYield(convertToDecimal(jsonObject.getOrDefault("yield", "").toString()));
                dsstoreBill.setArriveAmount(convertToDecimal(jsonObject.getOrDefault("ArriveAmount", "").toString()));
                dsstoreBill.setItemName(jsonObject.getOrDefault("ItemName", "").toString());
                dsstoreBill.setSysBatchCode(jsonObject.getOrDefault("SysBatchCode", "").toString());
                dsstoreBill.setCreateDate(convertToDate(jsonObject.getOrDefault("createDate", "").toString()));
                dsstoreBill.setAuditDate(convertToDate(jsonObject.getOrDefault("auditDate", "").toString()));
                dsstoreBill.setOtherSideId(jsonObject.getOrDefault("OtherSideID", "").toString());
                dsstoreBill.setBillType(jsonObject.getOrDefault("BillType", "").toString());
                dsstoreBill.setSellTaxMoney(convertToDecimal(jsonObject.getOrDefault("SellTaxMoney", "").toString()));
                dsstoreBill.setBillBusTypeId(jsonObject.getOrDefault("BillBusTypeId", "").toString());
                dsstoreBill.setPushInStoreAmount(convertToDecimal(jsonObject.getOrDefault("PushInStoreAmount", "").toString()));
                dsstoreBill.setInBusAmount(convertToDecimal(jsonObject.getOrDefault("InBusAmount", "").toString()));
                dsstoreBill.setBusDate(convertToDate(jsonObject.getOrDefault("busDate", "").toString()));
                dsstoreBill.setAPYear(convertToLong(jsonObject.getOrDefault("APYear", "").toString()));
                dsstoreBill.setItemBigClassCode(jsonObject.getOrDefault("ItemBigClassCode", "").toString());
                dsstoreBill.setSaleMoney(convertToDecimal(jsonObject.getOrDefault("SaleMoney", "").toString()));
                dsstoreBill.setStoreId(jsonObject.getOrDefault("StoreID", "").toString());
                dsstoreBill.setItemAbc(jsonObject.getOrDefault("ItemAbc", "").toString());
                dsstoreBill.setArrivalDate(convertToDate(jsonObject.getOrDefault("ArrivalDate", "").toString()));
                dsstoreBill.setAPMonth(convertToInt(jsonObject.getOrDefault("APMonth", "").toString()));
                dsstoreBill.setOtherSideCode(jsonObject.getOrDefault("OtherSideCode", "").toString());
                dsstoreBill.setBusUnit(jsonObject.getOrDefault("BusUnit", "").toString());
                dsstoreBill.setIncludeTaxMoney(convertToDecimal(jsonObject.getOrDefault("IncludeTaxMoney", "").toString()));
                dsstoreBill.setParentBillNo(jsonObject.getOrDefault("ParentBillNO", "").toString());
                list.add(dsstoreBill);
            }
        }

        //分批插入数据
        if (list.size() > 0) {
            for (DsstoreBill dsstoreBill : list) {
                try {
                    this.save(dsstoreBill);
                } catch (Exception e) {
                    System.out.println("======================" + dsstoreBill.toString());
                }


            }
        }

        logger.info("门店库存流水入库数据：{}条数据,数据时间：{}", list.size(), day);
        return list.size();
    }

    @Override
    public List<DsstoreBill> getConutData(DsstoreBillParam param) {
//        DsstoreBillParam param=new DsstoreBillParam();
//        param.setShopCode(shopCode);
//        param.setStartTime(startTime);
//        param.setEndTime(endTime);
//        param.setItemTypeCode(itemTypeCode);

        List<DsstoreBill> conutData =this.baseMapper.getConutData(param) ;
        return conutData;
    }

    /**
     * 获取转为商务单位为的数据
     *
     * @param param
     * @return
     */
    public List<DsstoreBill> getConutDataResult(DsstoreBillParam param) {
        //获取汇总数据
        List<DsstoreBill> conutDataList = this.baseMapper.getConutData(param);
        if (CollectionUtil.isNotEmpty(conutDataList)) {
            //获取所有品项的商务单位
            List<ItemBusUnitParam> allItemBusUnitList = itemInterfaceService.getAllItemBusUnit();
            Map<String, ItemBusUnitParam> unitMap = new HashMap<>();
            for (ItemBusUnitParam itemBusUnitParam : allItemBusUnitList) {
                unitMap.put(itemBusUnitParam.getItemCode(), itemBusUnitParam);
            }
            //换单位

            for (DsstoreBill dsstoreBill : conutDataList) {
                BigDecimal itemBalanceAmount = dsstoreBill.getItemBalanceAmout();
                //对应的商务单位数据
                ItemBusUnitParam item = unitMap.get(dsstoreBill.getItemCode());
                //单位
                dsstoreBill.setItemBusUnit(item.getItemUnitName());
                //换算
                BigDecimal itemBalanceBusAmout = BigDecimal.ZERO;
                if (itemBalanceAmount != null && itemBalanceAmount.compareTo(BigDecimal.ZERO) != 0) {
                    itemBalanceBusAmout = itemBalanceAmount.divide(item.getUnitRatio(), 6, BigDecimal.ROUND_UP);
                }
                dsstoreBill.setItemBalanceBusAmout(itemBalanceBusAmout);
            }
        }
        return conutDataList;
    }


    private Serializable getKey(DsstoreBillParam param) {
        return param.getId();
    }

    private Page getPageContext() {
        return LayuiPageFactory.defaultPage();
    }

    private DsstoreBill getOldEntity(DsstoreBillParam param) {
        return this.getById(getKey(param));
    }

    private DsstoreBill getEntity(DsstoreBillParam param) {
        DsstoreBill entity = new DsstoreBill();
        ToolUtil.copyProperties(param, entity);
        return entity;
    }

    /**
     * 转换时间格式
     *
     * @param time 参数
     * @return 转换之后的时间格式
     */
    public static String convertTime(String time) {
        // May 31, 2020 1:43:39 PM
        Date date = new Date(time);
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        time = simpleDateFormat.format(date);
        return time;
    }

    /**
     * 处理不合理数据，0E-8，0e-8
     */
    private String convertNum(String data) {
        if ("0E-8".equals(data) || "0-8".equals(data) || "0E-12".equals(data) || "0e-12".equals(data)) {
            return "0";
        } else {
            return data;
        }
    }


    /**
     * 转换数字为decimal
     *
     * @param data 参数
     * @return
     */
    public static BigDecimal convertToDecimal(String data) {
        if (StringUtils.isBlank(data) || "0E-8".equals(data) || "0-8".equals(data) || "0E-12".equals(data) || "0e-12".equals(data)) {
            return BigDecimal.ZERO;
        }
        BigDecimal decimal = new BigDecimal(data);
        return decimal;
    }

    public static Date convertToDate(String time) {
        if (StringUtils.isBlank(time)) {
            return null;
        }
        Date date = new Date(time);
        return date;
    }

    public static Integer convertBooleanToInt(String flag) {
        if (flag.equals("false")) {
            return 0;
        } else if (flag.equals("true")) {
            return 1;
        }
        return null;
    }

    public static Integer convertToInt(String data) {
        if (StringUtils.isBlank(data) || "0E-8".equals(data) || "0-8".equals(data) || "0E-12".equals(data) || "0e-12".equals(data)) {
            return 0;
        }
        Integer integer = Integer.valueOf(data);
        return integer;
    }

    public static Long convertToLong(String data) {
        if (StringUtils.isBlank(data) || "0E-8".equals(data) || "0-8".equals(data) || "0E-12".equals(data) || "0e-12".equals(data)) {
            return 0L;
        }
        Long lon = Long.valueOf(data);
        return lon;
    }
}
